//
//  KZTabBar.m
//  DuoChong
//
//  Created by 唐开江 on 14/11/24.
//  Copyright (c) 2014年 KangZhi. All rights reserved.
//

#import "KZTabBar.h"
#import "KZTabBarItem.h"


@interface KZTabBar ()

@property (nonatomic,strong)NSMutableArray * tabBarItemArray;

@property (nonatomic,strong)KZTabBarItem * selectedBtn;

@property (nonatomic,strong)KZTabBarItem * tabBarItem;

@end


@implementation KZTabBar

- (NSMutableArray *)tabBarItemArray
{
    if (_tabBarItemArray ==nil) {
        _tabBarItemArray = [NSMutableArray array];
    }
    return _tabBarItemArray;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        if (iOS8) {
        
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
        UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
        [self addSubview:effectview];
        }
    }
    return  self;
}



- (void)layoutSubviews
{
    [super layoutSubviews];
  
    
    //设置tabBarItem 的frame
    NSUInteger totalcount = self.tabBarItemArray.count;
    for (int i= 0; i<totalcount; i++) {
        KZTabBarItem * btn = self.tabBarItemArray[i];
        CGFloat w = self.width/totalcount;
        CGFloat h = self.height;
        CGFloat x= w*i;
        CGFloat y= 0;

        btn.frame = CGRectMake(x,y, w, h);
        [btn setTag:i];
        
    }

    if (iOS8) {
        for (UIView *view  in self.subviews) {
            if ([view isKindOfClass:[UIVisualEffectView class]] ) {
                UIVisualEffectView *effectview  = (UIVisualEffectView *) view;
                effectview.frame = self.bounds;
            }
            
        }
        
    }
    


}

- (void)addTabBarItem:(UITabBarItem *)tabBarItem withImageStr:(NSString *)str selectedImageStr:(NSString *)selectedStr
{
    
    
    
    //自定义tabBarItem
    KZTabBarItem * btn = [[KZTabBarItem alloc]init];
    btn.tabBarItem = tabBarItem;
    [btn setImage:[UIImage imageNamed:str] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selectedStr] forState:UIControlStateSelected];
    
    //添加监听事件
    [btn addTarget:self  action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    [self addSubview:btn];
    
    
    
    //添加到数组
    [self.tabBarItemArray addObject:btn];
    if (self.tabBarItemArray.count==1) {
        [self btnClick:btn];
        
    }
    
}

#pragma mark --点击事件


- (void)btnClick:(KZTabBarItem *)btn
{
    //切换控制器的代理
    if ([self.delegate respondsToSelector:@selector(KZTabBar:swithfrom:to:)]) {
        [self.delegate KZTabBar:self swithfrom:self.selectedBtn.tag to:btn.tag];
    }
    

    self.selectedBtn.selected = NO;
    self.selectedBtn = btn;
    self.selectedBtn.selected = YES;

}




@end
